<?php


namespace app\api\controller\v1;

use app\api\enum\Communication;
use app\api\service\Token;
use app\BaseController;
use app\Request;
use think\exception\HttpException;
use app\api\enum\User as UserEnum;
use app\api\model\User as UserModel;
use app\api\model\Communication as CommunicationModel;
use app\api\enum\Communication as CommunicationEnum;
use app\api\service\Token as TokenService;


class Chat extends BaseController
{
    /**
     * 文本消息的数据持久化
     */
    public function saveMessage(){
        if (request()->isPost()){
            $token = request()->header('token');
            TokenService::verifyToken($token);

            $message = input('post.');
            $datas = [
                'fromid' => $message['fromid'],
                'fromname' => $this->getIdName($message['fromid']),
                'toid' => $message['toid'],
                'toname' => $this->getIdName($message['toid']),
                'content' => $message['data'],
                'time' => $message['time'],
//                'isread' => $message['isread'],
                'isread' => CommunicationEnum::uread,
                'type' => UserEnum::type
            ];

            CommunicationModel::add($datas);
            return show(config('status.success'),"ok",[],200);
        }
        throw new HttpException(404,"非法请求");
    }

    /**
     * 根据用户id查询用户姓名
     */
    public function getIdName($uid){
        $res = UserModel::getIdName($uid);
        return $res;
    }

    /**
     * 根据用户id获取聊天双方头像信息
     */
    public function getHeadImg(){
        if (request()->isPost()){
            $res = UserModel::getHeadImg(input('post.'));
            return show(config('status.success'),"ok",$res,200);
        }
        throw new HttpException(404,"非法请求");
    }

    /**
     * 通过id获取单个用户昵称
     */
    public function getNickName(){
        if (request()->isPost()){
            $res = UserModel::getNickName(input('post.toid'));
            return show(config('status.success'),"ok",$res,200);
        }
        throw new HttpException(404,"非法请求");
    }

    /**
     * 通过聊天双方id获取聊天记录
     */
    public function messageLoad(){
        if (request()->isPost()){
            $res = CommunicationModel::messageLoad(input('post.'));
            return show(config('status.success'),"ok",$res,200);
        }
        throw new HttpException(404,"非法请求");
    }

    /**
     * 上传图片，返回图片地址
     */
    public function uploadImg(){
        if (request()->isPost()){
            //获取表单上传文件
            $file = request()->file('image');
            $suffix = substr(strrchr($file->getOriginalName(), "."), 1); // 文件后缀


            if(!in_array($suffix, config('upload.suffix_arr.image'))){
                throw new HttpException(404,"请上传格式为'".json(',',['jpg','jpeg','png','gif'])."'的文件");
            }

            if($file->getSize() > config('upload.size_arr.image')){ // 最大上传10M
                throw new HttpException(404,"上传的文件大小不能超过10M");
            }
            //上传文件到本地服务器
            $filename = \think\facade\Filesystem::disk('public')->putFile('', $file);

            if ($filename){
                // 上传成功 路径存入数据库
                $name = str_replace("\\","/",'/uploads/'.$filename);
                $data = [
                    'content' => config('upload.suffix_http').$name ,
                    'fromid' => input('fromid'),
                    'toid' => input('toid'),
                    'fromname' => $this->getIdName(input('fromid')),
                    'toname' => $this->getIdName(input('toid')),
                    'time' => time(),
//                    'isread' => input('online') == 1 ? Communication::read : Communication::uread,
                    'isread' => Communication::uread,
                    'type' => CommunicationEnum::image
                ];

                $insert = CommunicationModel::insert($data);
                if($insert){
                    return show(config('status.success'),"ok",['img_name'=>config('upload.suffix_http').$name],200);
                }
                throw new HttpException(404,"发送失败,图片路径保存失败!");
            }else{
                throw new HttpException(404,"文件上传失败");
            }
        }
        throw new HttpException(404,"非法请求");
    }

    /**
     * 根据uid获取当前用户聊天列表
     */
    public function getIdList(){
        if(request()->post()){
            $token = request()->header('token');
            TokenService::verifyToken($token);

            $res = CommunicationModel::getIdList(input('post.id'));
            if (sizeof($res) > 0) {
                return show(config('status.success'), "ok", $res, 200);
            } else {
                throw new HttpException(200, "当前没有对话列表");
            }
        }
        throw new HttpException(404,"非法请求");
    }

    /**
     * 通过消息id标记当前消息已读
     */
    public function isRead(){
        if(request()->post()){
            $token = request()->header('token');
            TokenService::verifyToken($token);

            $res = CommunicationModel::isRead(input('post.'));
            if ($res > 0) {
                return show(config('status.success'), "ok", $res, 200);
            } else {
                throw new HttpException(200, "标记已读失败");
            }
        }
        throw new HttpException(404,"非法请求");
    }


}